package com.bieyang.anjia.utils;

import java.io.File;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;

import org.json.JSONObject;

import android.animation.ValueAnimator;
import android.animation.ValueAnimator.AnimatorUpdateListener;
import android.annotation.SuppressLint;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.Environment;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;

import com.bieyang.anjia.R;
import com.bieyang.anjia.module.Device;
import com.bieyang.anjia.module.FileModel;
import com.bieyang.anjia.sqlitedatabase.SqliteOperation;
import com.bieyang.anjia.ui.activity.App;
import com.bieyang.anjia.ui.activity.SubMain;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;

public class SubUtils {
	/**
	 * 将已选择的星期几的Set<String>转化为TreeSet<Integer>
	 * 
	 * @param context
	 *            上下文
	 * @param set
	 *            星期集合
	 * */
	public TreeSet<Integer> getWeekDaySet(Context context, Set<String> set) {
		TreeSet<Integer> treeSet = new TreeSet<Integer>();
		if (null != set) {
			if (set.contains(context.getString(R.string.sub_week_monday))) {
				treeSet.add(2);
			}
			if (set.contains(context.getString(R.string.sub_week_tuesday))) {
				treeSet.add(3);
			}
			if (set.contains(context.getString(R.string.sub_week_wednesday))) {
				treeSet.add(4);
			}
			if (set.contains(context.getString(R.string.sub_week_thursday))) {
				treeSet.add(5);
			}
			if (set.contains(context.getString(R.string.sub_week_friday))) {
				treeSet.add(6);
			}
			if (set.contains(context.getString(R.string.sub_week_saturday))) {
				treeSet.add(7);
			}
			if (set.contains(context.getString(R.string.sub_week_sunday))) {
				treeSet.add(1);
			}
		}
		return treeSet;
	}

	/**
	 * 将设置信息保存在本地
	 * 
	 * @param device
	 *            设置信息模型
	 * @param con
	 */
	public void saveSubSet(Device device, Context con) {
		SharedPrefsUtil.putValue(con, Constants.DAY_MODE_START_TIME,
				device.getStartTWhite());
		SharedPrefsUtil.putValue(con, Constants.DAY_MODE_STOP_TIME,
				device.getEndTWhite());
		SharedPrefsUtil.putValue(con, Constants.AlARM_PLAY_VOICE,
				device.getDeterrenceVWhite());
		SharedPrefsUtil.putValue(con, Constants.NIGHT_MODE_START_TIME,
				device.getStartTNight());
		SharedPrefsUtil.putValue(con, Constants.NIGHT_MODE_STOP_TIME,
				device.getEndTNight());

		SharedPrefsUtil.putValue(
				con,
				Constants.ALARM_MEASURES,
				device.isHumanR() ? con.getString(R.string.sub_body_recg) : con
						.getString(R.string.sub_dys));
		SharedPrefsUtil.putValue(con, Constants.FLASH_LIGHT,
				device.isFlashlight());

		saveWeek(device.getWeekWhite(), con);
		String method = device.getLarmWhite();
		if (method.equals("TAKE_A_PICTURE")) {
			method = con.getString(R.string.sub_take_one);
		} else if (method.equals("CONTINUOUS_TREE")) {
			method = con.getString(R.string.sub_take_three);
		} else if (method.equals("MICRO_V_S")) {
			method = con.getString(R.string.sub_take_video);
		}
		SharedPrefsUtil.putValue(con, Constants.AlARM_METHODS, method);
	}

	/**
	 * 设置每周几天
	 * 
	 * @param weekDay
	 *            示例:1,2,3
	 * @param con
	 */
	private void saveWeek(String weekDay, Context con) {
		TreeSet<Integer> chooseDay = new TreeSet<Integer>();
		if (null != weekDay && !weekDay.isEmpty()) {
			String weekArr[] = weekDay.split(",");
			try {
				for (int i = 0; i < weekArr.length; i++) {
					chooseDay.add(Integer.parseInt(weekArr[i]));
				}
			} catch (Exception e) {
				// TODO: handle exception
			}
		} else {
			for (int i = 0; i < 7; i++) {
				chooseDay.add(i + 1);
			}
		}
		SharedPrefsUtil.putSetValue(con, Constants.WEEK_DAY,
				new SubUtils().getWeekSet(con, chooseDay));

	}

	/**
	 * 初始化星期集合
	 * 
	 * @param context
	 * @return set
	 */
	public HashSet<String> initWeekSet(Context context) {
		HashSet<String> set = new HashSet<String>();
		set.add(context.getString(R.string.sub_week_sunday));
		set.add(context.getString(R.string.sub_week_monday));
		set.add(context.getString(R.string.sub_week_tuesday));
		set.add(context.getString(R.string.sub_week_wednesday));
		set.add(context.getString(R.string.sub_week_thursday));
		set.add(context.getString(R.string.sub_week_friday));
		set.add(context.getString(R.string.sub_week_saturday));
		return set;
	}

	/**
	 * 生成二维码
	 * 
	 * @param content
	 *            内容
	 * @param size
	 *            尺寸
	 * @return bitmap
	 */
	public Bitmap createQRImage(String content, int size) {
		try {
			if (content == null || content.trim().isEmpty()) {
				return null;
			}
			Hashtable<EncodeHintType, String> hints = new Hashtable<EncodeHintType, String>();
			hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
			BitMatrix bitMatrix = new QRCodeWriter().encode(content,
					BarcodeFormat.QR_CODE, size, size, hints);
			int[] pixels = new int[size * size];
			for (int y = 0; y < size; y++) {
				for (int x = 0; x < size; x++) {
					if (bitMatrix.get(x, y)) {
						pixels[y * size + x] = 0xff000000;
					} else {
						pixels[y * size + x] = 0xffffffff;
					}
				}
			}
			Bitmap bitmap = Bitmap.createBitmap(size, size,
					Bitmap.Config.ARGB_8888);
			bitmap.setPixels(pixels, 0, size, 0, 0, size, size);
			return bitmap;
		} catch (WriterException e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 生成本机uuid
	 * 
	 * @param context
	 * @return
	 */
	public static String getUuid(Context context) {
		TelephonyManager tm = (TelephonyManager) context
				.getSystemService(Context.TELEPHONY_SERVICE);
		String tmDevice, subscriberId, androidId;
		tmDevice = "" + tm.getDeviceId();
		if (null != tmDevice && !tmDevice.trim().isEmpty()) {
			return tmDevice;
		}

		if (TelephonyManager.SIM_STATE_ABSENT == tm.getSimState()) {
			Log.d("GetUUid", "请确认sim卡是否插入或者sim卡暂时不可用！");
		} else {
			subscriberId = tm.getSubscriberId();
			if (null != subscriberId && !subscriberId.trim().isEmpty()) {
				return subscriberId;
			}
		}
		androidId = ""
				+ android.provider.Settings.Secure.getString(
						context.getContentResolver(),
						android.provider.Settings.Secure.ANDROID_ID);
		if (null != androidId && !androidId.trim().isEmpty()) {
			return androidId;
		}
		return "0000000000000000";
	}

	/**
	 * 得到每周工作日设置集合
	 * 
	 * @param context
	 * @param indexSet
	 * @return set
	 */
	public Set<String> getWeekSet(Context context, TreeSet<Integer> indexSet) {
		if (null == indexSet || 0 == indexSet.size()) {
			return null;
		} else {
			Set<String> set = new HashSet<String>();
			if (indexSet.contains(2)) {
				set.add(context.getString(R.string.sub_week_monday));
			}
			if (indexSet.contains(3)) {
				set.add(context.getString(R.string.sub_week_tuesday));
			}
			if (indexSet.contains(4)) {
				set.add(context.getString(R.string.sub_week_wednesday));
			}
			if (indexSet.contains(5)) {
				set.add(context.getString(R.string.sub_week_thursday));
			}
			if (indexSet.contains(6)) {
				set.add(context.getString(R.string.sub_week_friday));
			}
			if (indexSet.contains(7)) {
				set.add(context.getString(R.string.sub_week_saturday));
			}
			if (indexSet.contains(1)) {
				set.add(context.getString(R.string.sub_week_sunday));
			}
			return set;
		}

	}

	/**
	 * 初始化语音集
	 * 
	 * @param context
	 * @return voiceKeyAndId
	 */
	public HashMap<String, Integer> getVoiceMap(Context context) {
		HashMap<String, Integer> voiceKeyAndId = new HashMap<String, Integer>();
		voiceKeyAndId.put(context.getString(R.string.sub_alarm_voice1),
				R.raw.dog);
		voiceKeyAndId.put(context.getString(R.string.sub_alarm_voice3),
				R.raw.notify_management);
		voiceKeyAndId.put(context.getString(R.string.sub_child_voice1),
				R.raw.huma);
		voiceKeyAndId.put(context.getString(R.string.sub_child_voice4),
				R.raw.wenrou);
		return voiceKeyAndId;
	}

	/**
	 * 获取文件夹路径
	 * 
	 * @param context
	 * @return fileFolderPath 文件夹路径
	 */
	public String getFileFloderPath(Context context) {
		String fileFolderPath = null;
		if (!Environment.getExternalStorageState().equals(
				Environment.MEDIA_MOUNTED)) {
			// Show.toast(context, "no sdcard!");
			fileFolderPath = context.getFilesDir().getPath() + "/";
			return fileFolderPath;
		}
		fileFolderPath = Environment.getExternalStorageDirectory() + "/"
				+ Constants.AUDIO_RECORDER_FOLDER + "/";
		File fileFolder = new File(fileFolderPath);
		if (!fileFolder.exists()) { // 如果目录不存在，则创建一个目录
			boolean isSuccess = fileFolder.mkdir();
			if (!isSuccess) {
				fileFolder = null;
			}
		}
		return fileFolderPath;
	}

	/**
	 * 清理过期文件
	 * 
	 * @param context
	 */
	@SuppressLint("SimpleDateFormat")
	public void clearFile(Context context) {
		File file = new File(getFileFloderPath(context));
		String[] childFile = file.list();
		for (String name : childFile) {
			if (name.startsWith("20")) {
				String format = name.substring(0, 14);
				try {
					long millis = new SimpleDateFormat("yyyyMMddHHmmss").parse(
							format).getTime();
					if ((System.currentTimeMillis() - millis)
							/ (1000 * 60 * 60 * 24) > 7) {
						File fileChild = new File(file, name);
						fileChild.delete();
					}
				} catch (ParseException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
	}

	/**
	 * 上传七牛文件路径给安加服务器
	 * 
	 * @param fileSize
	 *            文件大小
	 * @param key
	 *            七牛key
	 * @param fileType
	 *            文件类型
	 * @param context
	 */
	public void upLoadFilePath(int fileSize, String key, String fileType,
			Context context) {
		App.netManager
				.qiniuSaveFile(fileSize, key, SubMain.AlarmType, fileType);
	}

	/**
	 * 在状态栏显示通知
	 */

	@SuppressWarnings("deprecation")
	public static void showNotification(String title, String content,
			Context context, Class<?> cls) {
		// 创建一个NotificationManager的引用
		NotificationManager notificationManager = (NotificationManager) context
				.getSystemService(android.content.Context.NOTIFICATION_SERVICE);
		// 定义Notification的各种属性
		Notification notification = new Notification(R.drawable.head_notify,
				title, System.currentTimeMillis());
		// FLAG_AUTO_CANCEL 该通知能被状态栏的清除按钮给清除掉
		// FLAG_NO_CLEAR 该通知不能被状态栏的清除按钮给清除掉
		// FLAG_ONGOING_EVENT 通知放置在正在运行
		// FLAG_INSISTENT 是否一直进行，比如音乐一直播放，知道用户响应
		notification.flags |= Notification.FLAG_AUTO_CANCEL;
		// notification.flags |= Notification.FLAG_ONGOING_EVENT; //
		// 将此通知放到通知栏的"Ongoing"即"正在运行"组中
		// notification.flags |= Notification.FLAG_NO_CLEAR; //
		// 表明在点击了通知栏中的"清除通知"后，此通知不清除，经常与FLAG_ONGOING_EVENT一起使用
		notification.flags |= Notification.FLAG_SHOW_LIGHTS;
		// DEFAULT_ALL 使用所有默认值，比如声音，震动，闪屏等等
		// DEFAULT_LIGHTS 使用默认闪光提示
		// DEFAULT_SOUNDS 使用默认提示声音
		// DEFAULT_VIBRATE 使用默认手机震动，需加上<uses-permission
		// android:name="android.permission.VIBRATE" />权限
		notification.defaults = Notification.DEFAULT_LIGHTS;
		// 叠加效果常量
		// notification.defaults=Notification.DEFAULT_LIGHTS|Notification.DEFAULT_SOUND;
		notification.ledARGB = Color.BLUE;
		notification.ledOnMS = 5000; // 闪光时间，毫秒
		// 设置通知的事件消息
		CharSequence contentTitle = title; // 通知栏标题
		CharSequence contentText = content; // 通知栏内容
		Intent notificationIntent = new Intent(context, cls); // 点击该通知后要跳转的Activity
		notificationIntent.putExtra("formNotification", true);
		notificationIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		PendingIntent contentItent = PendingIntent.getActivity(context, 0,
				notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
		notification.setLatestEventInfo(context, contentTitle, contentText,
				contentItent);

		// 把Notification传递给NotificationManager
		notificationManager.notify(0, notification);
	}

	/**
	 * 删除通知
	 * 
	 * @param context
	 */
	public static void clearNotification(Context context) {
		// 启动后删除之前我们定义的通知
		NotificationManager notificationManager = (NotificationManager) context
				.getSystemService(android.content.Context.NOTIFICATION_SERVICE);
		notificationManager.cancel(0);
	}

	/**
	 * 显示更新动画
	 * 
	 * @param context
	 * @return progressDialog
	 */
	public static ShowProgress showProgress(Context context) {
		ShowProgress progressDialog = new ShowProgress(context);
		progressDialog.setMessage(R.string.loadingText);
		progressDialog.show();
		return progressDialog;
	}

	/**
	 * 保存数据到本地数据库
	 * 
	 * @param data
	 */
	public void saveDataToDataBase(Context con, SqliteOperation operation,
			JSONObject json) {
		try {
			FileModel model = new FileModel();
			model.uuid = json.getString("uuid");
			if (TextUtils.equals("null", model.uuid)) {
				return;
			}
			String alarmType = json.getString("alarmType");
			if (alarmType.equals("HUMAN_RECOGNITION")) {
				alarmType = con.getString(R.string.sub_body_recg);
			} else if (alarmType.equals("MOTION_DETECTION")) {
				alarmType = con.getString(R.string.sub_dys);
			} else if (alarmType.equals("ZHONG_MOVING")) {
				alarmType = con.getString(R.string.sub_moved);
			}
			model.infoId = json.getInt("id");
			model.alarmType = alarmType;
			model.time = json.get("alarmTime").toString();

			model.memberId = json.get("memberId").toString();
			model.alarmId = json.getInt("alarmId");
			model.name = json.getString("name");
			Log.e("model.time", model.time + "----");
			operation.insert("alarminfo", model);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 删除动画
	 * 
	 * @param view
	 * @param position
	 * @param list
	 *            数据集
	 * @param adapter
	 */
	public void startDeleteAnimation(final View view, final int position,
			final List<?> list, final BaseAdapter adapter) {
		final ValueAnimator mAnimator = ValueAnimator.ofFloat(0, 1)
				.setDuration(500);
		final int height = view.getHeight();
		mAnimator.addUpdateListener(new AnimatorUpdateListener() {

			@Override
			public void onAnimationUpdate(ValueAnimator animation) {
				float progress = Float.parseFloat(animation.getAnimatedValue()
						.toString());
				if (progress > 0.9f) {
					try {
						list.remove(position);
						adapter.notifyDataSetChanged();
					} catch (IndexOutOfBoundsException e) {
						e.printStackTrace();
					}
					ViewGroup.LayoutParams params = view.getLayoutParams();
					params.height = ViewGroup.LayoutParams.WRAP_CONTENT;
					view.setLayoutParams(params);
					view.setAlpha(1);
					mAnimator.cancel();
				} else {
					view.setAlpha(1 - progress);
					ViewGroup.LayoutParams params = view.getLayoutParams();
					params.height = (int) ((1 - progress) * height);
					view.setLayoutParams(params);
				}
			}
		});
		mAnimator.start();
	}
}
